<template>
  <div class="updataArticle">
    <!-- 编辑面板 -->
    <el-dialog :fullscreen="true" :visible.sync="dialogVisible" :close="dialogVisible_item_close">
      <h2>文章添加</h2>

      <el-form class="form1" :label-position="labelPosition" label-width="80px" :model="form_item" :rules="rules1"
        ref="form_item">
        <el-form-item label="封面">
          <el-upload action="none" list-type="picture-card" :on-remove="handleRemove" :on-change="check_file"
            :auto-upload="false" :drag="false" :multiple="false" :show-file-list="false">
            <img v-if="uploadURL" :src="uploadURL" style="width: 100%" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <el-dialog :visible.sync="dialogVisible_item2">
              <img width="100%" height="100%" :src="image_item2" alt="加载失败" />
            </el-dialog>
          </el-upload>
        </el-form-item>
        <el-form-item class="confim_isok">
          <el-button @click="dialogVisible_item_close">取 消</el-button>
          <el-button type="primary" @click="submit_insertdata('form_item')">发 布</el-button>
        </el-form-item>
        <el-form-item label="分类名称" style="width: 50%" prop="classID">
          <el-select v-model="classID" placeholder="请选择">
            <el-option v-for="item in classList" :key="item.classID" :label="item.className" :value="item.classID"
              :disabled="item.active == 0">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="标签名称" style="width: 50%">
          <template>
            <el-select v-model="check_tagitem" multiple placeholder="请选择">
              <el-option v-for="item in tag_items" :key="item.tagID" :label="item.tagName" :value="item.tagID"
                :disabled="item.active == 0">
              </el-option>
            </el-select>
          </template>
        </el-form-item>
        <el-form-item label="标题" prop="title" style="width: 50%">
          <el-input v-model="form_item.title"></el-input>
        </el-form-item>
        <el-form-item label="摘要" style="width: 50%">
          <el-input v-model="form_item.summary"></el-input>
        </el-form-item>

        <el-form-item label="点赞数" style="width: 50%">
          <template>
            <el-input-number v-model="form_item.likeCount" controls-position="right" :min="0" :max="99999999">
            </el-input-number>
          </template>
        </el-form-item>
        <el-form-item label="踩/个" style="width: 50%">
          <template>
            <el-input-number v-model="form_item.unlikeCount" controls-position="right" :min="0" :max="99999999">
            </el-input-number>
          </template>
        </el-form-item>
        <el-form-item label="浏览量" style="width: 50%">
          <template>
            <el-input-number v-model="form_item.viewCount" controls-position="right" :min="0" :max="99999999">
            </el-input-number>
          </template>
        </el-form-item>
        <el-form-item label="状态" style="width: 10%">
          <el-radio-group v-model="form_item.active">
            <template>
              <el-radio value="1" label="1">启用</el-radio>
              <el-radio value="0" label="0">禁用</el-radio>
            </template>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <!-- <el-input v-model="form_item.content"></el-input> -->
          <template>
            <div style="border: 1px solid #ccc">
              <Toolbar style="border-bottom: 1px solid #ccc" :editor="editor" :defaultConfig="toolbarConfig"
                :mode="mode" />
              <Editor style="height: 500px; overflow-y: hidden" v-model="form_item.content"
                :defaultConfig="editorConfig" :mode="mode" @onCreated="onCreated" />
            </div>
          </template>
        </el-form-item>
      </el-form>
      <!-- {{ form_item.content }} -->
    </el-dialog>
  </div>
</template>

<script>
/*导入上传图片 */
import { upload_img } from "@/request/api";
/*导入上传图片wang */
// import { upload_imgV2 } from "@/request/api";
/*导入添加*/
import { insertArticle } from "@/request/api";
/*导入获取标签 */
import { getTags } from "@/request/api";
/*导入获取分类 */
import { getclass_listV2 } from "@/request/api";
/*导入 富文本编辑器-wangeditor */
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
/**导入样式 */
import "@wangeditor/editor/dist/css/style.css";
export default {
  name: "shsCeshi",
  props: {
    articleID: {
      type: Number,
      default: 0,
    },
    dialogVisible_item: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      /*富文本编辑器*/
      editor: null,
      html: "<p>hello</p>",
      toolbarConfig: {},
      editorConfig: { placeholder: "请输入内容..." },
      mode: "default", // or 'simple'

      labelPosition: "right", //右对齐
      form_item: { title: null, active: "1" }, //文章数据
      dialogVisible: this.dialogVisible_item, //对话框显隐
      tag_items: {}, //标签列表
      classList: {}, //分类列表
      check_tagitem: [], //选中的标签
      classID: null, //选中的分类id
      dialogVisible_item2: false, //预览图 显示隐藏 标识
      image_item2: null, //预览图url
      uploadURL: "", //上传图片的URL
      currentFile: null, //最新图片实例
      rules1: {
        title: [
          { required: true, message: "请输入标题", trigger: "blur" },
          {
            min: 2,
            max: 50,
            message: "长度在 2 到 50 个字符",
            trigger: "blur",
          },
        ],
        content: [
          { required: true, message: "内容不能为空", trigger: "blur" },
          { min: 5, message: "长度应大于5个字符", trigger: "blur" },
        ],
      },
    };
  },

  /**挂载之后 */
  mounted() { },
  methods: {
    /**富文本编辑器 创建后 */
    onCreated(editor) {
      editor.getMenuConfig('uploadImage').server = "/api/upload_file_imageV2";//上传图片
      // editor.getMenuConfig('uploadVideo').headers = { 'authorization': localStorage.getItem("usertoken") }
      editor.getMenuConfig('uploadVideo').fieldName = "wangeditor-uploaded-video";//视频文件名称
      editor.getMenuConfig('uploadVideo').server = "https://shsnum.xyz/upload_file_videoV2";//上传视频
      
      // 单个文件的最大体积限制，默认为 10M
      editor.getMenuConfig('uploadVideo').maxFileSize = 50 * 1024 * 1024, // 50M
      editor.getMenuConfig('uploadVideo').onError=(file, err,res)=>{  
        console.log(` 上传出错`, err.message, res)
        this.$message({message:err.message,type:"error"})
    }
        editor.getMenuConfig('uploadImage').headers = { 'authorization': localStorage.getItem("usertoken") }
      // editor.getMenuConfig('uploadImage') // 获取 uploadImage 的当前配置
      this.editor = Object.seal(editor); // 一定要用 Object.seal() ，否则会报错
    },
    //新增数据
    insertdata() {
      let obj = {
        cover: this.form_item.cover, //封面
        title: this.form_item.title, //标题
        summary: this.form_item.summary, //摘要
        content: this.form_item.content, //内容
        likeCount: this.form_item.likeCount, //点赞
        unlikeCount: this.form_item.unlikeCount, //踩
        viewCount: this.form_item.viewCount, //浏览量
        relation_id: this.form_item.relation_id, //关联id
        classID: this.classID, //分类
        tag_list_id: this.check_tagitem, //标签
        active: this.form_item.active, //是否启用
        createAt: new Date(), //创建时间
      };
      if (!this.currentFile && !obj.cover) {
        this.$message({ message: "请选择封面", type: "info" });
        return;
      }
      /*上传图片--封面 */
      let formdata = new FormData();
      //保存formdata
      formdata.append("single_image_file", this.currentFile.raw);
      upload_img(formdata)
        .then((data) => {
          if (data.data.code == 1) {
            obj.cover = data.data.path; //图片网址
            return insertArticle(obj);
          } else {
            /*封面上传失败*/
            this.$notify.error({
              message: data.data.msg,
            });
          }
        })
        .then((data) => {
          if (data.data.code == 200) {
            this.$notify({
              title: "Hint",
              message: data.data.msg,
              type: "success",
            });
            this.dialogVisible = false;
            this.form_item = { title: null, active: "1" }; //文章数据重置
            this.uploadURL = null;
            this.currentFile = null; //图片/图片实例重置
            this.$emit("list_change", true);
          } else {
            this.$message({ message: data.data.msg, type: "error" });
          }
        })
        .catch((err) => {
          this.$notify.error({
            message: err,
          });
        });
    },
    dialogVisible_item_close() {
      console.log("关闭后销毁数据");
      this.dialogVisible = false;
    },
    //提交按钮 更新数据
    submit_insertdata(form_item) {
      let _this = this;
      this.$refs[form_item].validate((vali) => {
        if (vali) {
          _this
            .$confirm("你确定要发布当前的数据吗")
            .then(() => {
              //调用发布的函数
              _this.insertdata();
            })
            .catch(() => { });
        }
      });
    },

    // 预览图
    handlePictureCardPreview(file) {
      this.dialogVisible_item2 = true;
      this.image_item2 = URL.createObjectURL(file.raw);
    },
    // 图片移除 清空当前图片实例
    handleRemove(file, fileList) {
      this.currentFile = null;
      console.log("file", file, "filelist", fileList);
    },
    //图片选择后
    check_file(file) {
      this.currentFile = file; // 赋值到最新图片实例
      this.uploadURL = URL.createObjectURL(file.raw); //创建对象的URL
      this.form_item.cover = URL.createObjectURL(file.raw);
    },
  },
  watch: {
    dialogVisible(val) {
      this.$emit("dialogVisible_item_change", val);
    },
    dialogVisible_item(val) {
      this.dialogVisible = val;
      if (val) {
        getclass_listV2({ begin_index: 0, page_size: 99999 })
          .then((data) => {
            if (data.data.code == 200) {
              this.classList = data.data.data.list;
              this.classID = this.classList[0].classID;
              return getTags({ begin_index: 0, page_size: 99999 });
            }
          })
          .then((data) => {
            if (data.data.code == 200) {
              this.tag_items = data.data.data.list;
            }
          });
      }
    },
  },
  computed: {},
  components: {
    Editor,
    Toolbar,
  },
  beforeDestroy() {
    const editor = this.editor;
    if (editor == null) return;
    editor.destroy(); // 组件销毁时，及时销毁编辑器
  },
};
</script>

<style scoped>
.form1 {
  margin: 20px 0;
}

.confim_isok {
  position: absolute;
  right: 30px;
}
</style>
